<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='name' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #chargeType="{record}">
            {{ chargingTypeMap[record.chargeType] }}
        </template>

        <template #file="{record}">
            <a-button shape="round" @click="dowloadFirmware(record.name, record.file)">
                <template #icon>
                    <DownloadOutlined />
                </template>
                下载
            </a-button>
        </template>

        <template #$action="{record}">
            <BTextButton @click="openUpgrade(record)">升级</BTextButton>
        </template>

    </BPTable>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form :layout='i18n.locale == "ZH" ? "horizontal" : "vertical"' ref='formRef' :label-col='{span : i18n.locale == "ZH" ? 5 : 24}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item label="类型" name="chargeType" :rules="[{required : true, message : '请选择类型'}]">
                <a-select v-model:value="formData.chargeType" :fieldNames="{label : 'name', value : 'code', options : 'children'}" :options="chargingTypeOptions"></a-select>
            </a-form-item>
            <a-form-item label="名称" name='name' :rules="[{required : true}]">
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.name' />
            </a-form-item>
            <a-form-item v-if="formData.id == 0" label="固件" name="file" :rules="[{required : true, message : '请选择固件'}]">
                <a-input type="hidden" v-model:value="formData.file" />
                <a-upload v-model:file-list='firmwares' :beforeUpload='beforeUpload' :customRequest="customRequest" @remove="removeFirmware">
                    <a-button>
                        <upload-outlined></upload-outlined>选择固件
                    </a-button>
                </a-upload>
            </a-form-item>
            <a-form-item label="备注" name='remark'>
                <a-input :maxlength='50' show-count type='text' v-model:value='formData.remark' />
            </a-form-item>
        </a-form>
        <!-- <BForm ref='formRef' :label-col='{span : 5}' :fields='formFields'></BForm> -->
    </BDialog>

    <BDialog v-model:visible='upgradeVisible' title='升级' width='600px' :confirm='upgrade'>
        <Upgrade ref="upgradeRef" :firmware="currentFirmware" />
    </BDialog>
    
</template>

<script lang='ts' setup>
    import { ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { DownloadOutlined, UploadOutlined } from '@ant-design/icons-vue';
    import { deleteApi, uploadFirmwareApi, pageApi, saveApi } from "@/api/Ota";
    import { parseTime, recursionFn } from "@/utils";
    import { useI18nStore } from "@/store/i18n";
    import { chargingTypeApi } from "@/api/devices/Device";
    import Upgrade from './Upgrade.vue'

    const i18n = useI18nStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const tableRef = ref()

    const upgradeRef = ref()
    const upgradeVisible = ref(false)
    const currentFirmware = ref()
    function openUpgrade(firmware) {
        currentFirmware.value = firmware
        upgradeVisible.value = true
    }
    async function upgrade() {
        upgradeRef.value.submit()
    }


    const buttons = ref<SearchButton[]>([])

    buttons.value.push({
        button : 'add',
        func : () => {
            dialogTitle.value = i18n.t('add')
            visible.value = true
        }
    })


    function dowloadFirmware(name:string, file:string) {
        const link = document.createElement('a');
        link.style.display = 'none';
        document.body.appendChild(link);
        link.href = import.meta.env.B_NET_STATIC_URL + file;
        link.download = name + '.' + (file.split('.').pop());
        link.click();
        document.body.removeChild(link);
    }


    const chargingTypeOptions = ref<any[]>([])
    const chargingTypeMap = ref<{[key:string]:string}>({})


    const formData = ref({
        id : 0,
        chargeType : '',
        name : '',
        size : 0,
        file : '',
        remark : '',
    })

    const firmwares = ref<any[]>([])

    function beforeUpload(file:File, field:FormField) {
        formData.value.size = file.size
        // const reader = new FileReader();
        // reader.onload = function(event) {
        //     if(event && event.target) {
        //         const contents = event.target.result;
        //         if(contents) {
        //             const bytes = new Blob([contents]).size;
        //             formData.value.size = bytes
        //         }
                
        //     }
            
        // };

        // reader.readAsBinaryString(file);

        //formData.value.firmware = file.name
        return true
    }

    function removeFirmware() {
        formData.value.file = ''
    }

    async function customRequest({ file }) {
        const res = await uploadFirmwareApi(file)
        formData.value.file = res.data
        firmwares.value[0].status = 'done'
        // const len = picsFiles.value.length
        //     picsFiles.value[len - 1].status = 'done'
        //     formData.value.pics.push(res.data)
    }



    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : i18n.t('name'),
            inSearch : true,
        },

        {
            dataIndex : 'chargeType',
            title : '充电类型',
        },

        {
            dataIndex : 'remark',
            title : '备注',
        },

        {
            dataIndex : 'size',
            title : '固件字节数',
        },

        {
            dataIndex : 'file',
            title : '固件'
        },


        {
            title : i18n.t('createTime'),
            dataIndex : 'createTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },

        
        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit : (row) => {
                dialogTitle.value = '更新'
                for(let k in formData.value) {
                    if(k != 'file') {
                        formData.value[k] = row[k]
                    }
                }
                visible.value = true
            },  

            $delete : async(row, index) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    tableRef.value.reload()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            }
            
        },
    ])



    function resetForm() {
        firmwares.value = []
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    

    async function submit() {
        try {
            let {...params}  = await formRef.value.validate()
            params.size = formData.value.size
            const res = await saveApi(params)
            if(res.success) {
                tableRef.value.reload()
                message.success(i18n.t('saveSuccess'))
                resetForm()
                visible.value = false
            }else {
                Modal.error({
                    title : res.msg
                })
            }
        } catch (error) {
            console.log(error)
        }
    }

    chargingTypeApi().then(res => {
        if(res.data.length > 0) {
            res.data.forEach(item => {
                chargingTypeMap.value[item.code] = i18n.t(item.name)
                item.code = Number(item.code)
                item.name = i18n.t(item.name)
            })

            let options = recursionFn(res.data, 0, 'id', 'parentId', 'children')


            chargingTypeOptions.value = options
            
        }
    })


</script>